package com.iflytek.jzcpx.procuracy.tools.cont;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iflytek.jzcpx.procuracy.common.util.IdWokerUtil;
import com.iflytek.jzcpx.procuracy.tools.common.enums.ToolsContstants;
import com.iflytek.jzcpx.procuracy.tools.cont.model.AcDto;
import com.iflytek.jzcpx.procuracy.tools.cont.model.CatalogInfoDTO;
import com.iflytek.jzcpx.procuracy.tools.cont.model.ContCatalogResultNew;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自动编目 客户端
 *
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2019-08-06 19:43
 */
public class ContClient {
    private static final Logger logger = LoggerFactory.getLogger(ContClient.class);

    private static final Map<String, Object> DEFAULT_PARAMS = new HashMap<>();

    static {
        DEFAULT_PARAMS.put("in_encode", "UTF8");
        DEFAULT_PARAMS.put("mode", "overwrite");
        DEFAULT_PARAMS.put("out_encode", "UTF8");
    }

    /** ocr 接口地址 */
    private final String SERVER_URL;

    public ContClient(String server, String path) {
        this.SERVER_URL = StringUtils.removeEnd(server, "/") + StringUtils.prependIfMissing(path, "/");
        logger.info("创建 Cont 客户端, 接口地址: {}", SERVER_URL);
    }

    public CatalogInfoDTO request(List<AcDto> acList) {
        Map<String, Object> contParam = new HashMap<>();
        contParam.put("trackId", IdWokerUtil.nextId() + "");
        contParam.put("param", DEFAULT_PARAMS);
        contParam.put("ocr_list", acList);
        String acJson = JSON.toJSONString(contParam);

        HttpResponse response = HttpRequest.post(SERVER_URL).header("Content-Type", "application/json; charset=UTF-8")
                                           .body(acJson).timeout(ToolsContstants.ENGINE_REQUEST_TIMEEOUT).execute();
        if (!response.isOk()) {
            logger.warn("请求编目引擎异常. url: {}", SERVER_URL);
            return null;
        }

        String body = response.body();
        JSONObject temp = JSONObject.parseObject(body);
        JSONObject tagTemp = JSONObject.parseObject((String) temp.get("tag"));
        temp.remove("tag");
        temp.put("tag", tagTemp);
        ContCatalogResultNew contCatalogResultNew = JSON.parseObject(temp.toString(), ContCatalogResultNew.class);
        if (0 == contCatalogResultNew.getState().getOk()) {
            logger.error("调用自动编目发生异常！！！！异常信息：{}", contCatalogResultNew);
            return null;
        }
        return contCatalogResultNew.getTag();
    }
}
